package utilities.print.menu.execute.main;

import employee.User;
import utilities.JDBC.Database;
import utilities.JDBC.sql.SelectUserName;
import utilities.print.log.Log;
import utilities.print.log.LogMessage;
import utilities.print.menu.MenuExecute;
import utilities.print.menu.execute.Verify;
import utilities.print.menu.pager.UserPager;

import java.sql.ResultSet;
import java.util.Scanner;

import static utilities.print.menu.Menu.emptyPrint;
import static utilities.print.menu.Menu.line;

public class Login implements MenuExecute {
    private final Database<User> database = new Database<>();

    /**
     * 启动菜单功能类方法
     * @throws Exception 可能产生的异常
     */
    @Override
    public void execute() throws Exception {
        Scanner in = new Scanner(System.in);
        User myUser = new User();
        System.out.println("登录页");
        line();

        System.out.print("输入登录的账户名字: ");
        myUser.setName(in.next());
        System.out.print("输入登录的账户密码: ");
        myUser.setPassword(in.next());

        if (!Verify.isVerified()){
            execute();
        }

        ResultSet set = database.executeSelect(new SelectUserName(myUser.getName()));
        if (set.next()){
            //数据库中的账号信息
            User user = database.toObject(
                    set,
                    new User()
                    );
            myUser.setId(user.getId());

            isLogin(user, myUser);
            database.close();
        }
    }

    private void isLogin(User user, User myUser) throws Exception {
        if (user.equals(myUser)){
            line();
            System.out.println("登录成功!");
            line();

            emptyPrint();
            UserPager.main(new String[]{
                    myUser.toString()
            });
        }else {
            System.out.println("登录失败!");
            if (Verify.isConfirm()){
                execute();
            }
        }
    }
}
